package com.hsj.mqconsumer.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 订阅模式的消费者
 * @author:Teacher黄
 * @date:Created at 2020/01/05
 */
@Component
public class SubConsumer {


    /**
     * 发布订阅模式的 消费者1
     * @param msg
     * @param headers
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "sub01",durable = "true",autoDelete = "false"),
            exchange = @Exchange(name = "pub_exchange",type = "fanout"),
            key = "pub_sub"
    ))
    @RabbitHandler
    public void sub(String msg, @Headers Map<String,Object> headers, Channel channel) throws IOException {

        System.out.println("消费者1接收到了消息:"+msg);
        // 获取deliverTag 消费标记
        long deliverTag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        // 手动ack
        channel.basicAck(deliverTag,true);
    }


    /**
     * 发布订阅模式的 消费者2
     * @param msg
     * @param headers
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "sub02",durable = "true",autoDelete = "false"),
            exchange = @Exchange(name = "pub_exchange",type = "fanout"),
            key = "pub_sub"
    ))
    @RabbitHandler
    public void sub02(String msg, @Headers Map<String,Object> headers, Channel channel) throws IOException {

        System.out.println("消费者2接收到了消息:"+msg);
        // 获取deliverTag 消费标记
        long deliverTag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        // 手动ack
        channel.basicAck(deliverTag,true);
    }
}
